import random
from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection
import logging
logger = logging.getLogger('django')
from meiduo_No3.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import ccp_send_sms_code

class ImageCode(View):
    def get(self,request,uuid):
        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s'%uuid,300,text)

        return HttpResponse(image,content_type='image/jpg')

class SmsCode(View):
    def get(self,request,mobile):
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s'%mobile)
        if send_flag:
            return JsonResponse({'code':400,
                                 'errmsg':'发送短信过于频繁'})

        image_code_client = request.GET.get("image_code")
        uuid = request.GET.get("image_code_id")

        if not all([image_code_client,uuid]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少必传的参数'})
        image_code_server = redis_conn.get('img_%s'%uuid)

        if image_code_server is None:
            return JsonResponse({'code':400,
                                 'errmsg':'图像验证码已过期'})
        try:
            redis_conn.delete('img_%s'%uuid)
        except Exception as e:
            logger.info(e)

        if image_code_client.lower() != image_code_server.decode().lower():
            return JsonResponse({'code':400,
                                 'errmag':'输入的图形验证码有误'})
        sms_code = '%06d'%random.randint(0,999999)
        logger.info(sms_code)
        pl = redis_conn.pipeline()
        pl.setex('sms_%s'%mobile,300,sms_code)
        pl.setex('send_flag_%s'%mobile,60,1)
        pl.execute()

        # ccp_send_sms_code.delay(mobile,sms_code)
        return JsonResponse({'code':0,
                             'errmsg':'发送短信成功'})

